import { BrowserWindow, app, shell } from 'electron';
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

let settingWin = null;

const createsettingWin = () => {
    settingWin = new BrowserWindow({
        title: 'ReadTool Setting',
        width: 400,
        height: 430,
        autoHideMenuBar: true,
        icon: icon,
        webPreferences: {
            nodeIntegration: true,
            preload: join(__dirname, '../preload/index.js'),
        },
        resizable: false,
        show:false

    });
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        settingWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        settingWin.loadFile(join(__dirname, '../renderer/index.html'))
    }
    // 假设你想在创建窗口后立即打开设置路由
    settingWin.webContents.on('did-finish-load', () => {
        settingWin.webContents.send('set-route', '/setting');
    });

    settingWin.webContents.setWindowOpenHandler((details) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return { action: 'deny' }
    })

    return settingWin;
}
function closesettingWin() {
    if (settingWin && !settingWin?.isDestroyed()) {
        settingWin?.close();
    }
    settingWin = null;
}

function opensettingWin() {
    if (!settingWin || settingWin?.isDestroyed()) {
        settingWin = createsettingWin();
    }
}
function showsettingWin(){
    settingWin?.show();
}
function hidesettingWin() {
    settingWin.hide();
}
// 写一个show和hide切换
function showHidesettingWin() {
    settingWin.isVisible() ? settingWin.hide() : settingWin.show();
}
function goHomesettingWin() {
    settingWin.loadURL('http://localhost:3456/setting')
}

function minimizesettingWin() {
    settingWin.minimize();
}

function focussettingWin() {
    if (!settingWin || settingWin?.isDestroyed()) {
        settingWin = createsettingWin();
    } else {
        // Focus on the main window if the user tried to open another
        if (settingWin.isMinimized()) settingWin.restore();
        if (!settingWin.isVisible()) settingWin.show();
        settingWin.focus();
    }
}

function sendEuUpdateCanAvailable(arg, update) {
    if (settingWin && !settingWin?.isDestroyed()) {
        settingWin.webContents.send('eu:update-can-available', {
            update: update,
            version: app.getVersion(),
            newVersion: arg?.version,
        });
    }
}

export {
    closesettingWin,
    createsettingWin,
    showsettingWin,
    focussettingWin,
    hidesettingWin,
    minimizesettingWin,
    opensettingWin,
    sendEuUpdateCanAvailable,
    showHidesettingWin,
    goHomesettingWin
};